#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <memory>
#include <unistd.h>
#include <ctime>
#include <sstream>
#include <filesystem> // C++17, 需要⾼版本编译器和-std=c++17
#include "Mutex.hpp"

//1.定制刷新策略

//文件路径 & 文件名 （默认）
const std::string defaultpath = "./log/";
const std::string defaultname = "log.txt";

//日志等级
enum class LogLevel
{
    DEBUG,
    INFO,
    WARNING,
    ERROR,
    FATAL
};
//打印日志等级
std::string level2string(LogLevel level)
{
    switch(level)
    {
        case LogLevel::DEBUG:
            return "Debug";
        case LogLevel::INFO:
            return "Info";
        case LogLevel::WARNING:
            return "Warning";
        case LogLevel::ERROR:
            return "Error";
        case LogLevel::FATAL:
            return "Fatal";
        default:
            return "Unknown";
    }
}

//获取时间
std::string Getcurrenttime()
{
    time_t currtime = time(nullptr);
    struct tm curr;
    localtime_r(&currtime, &curr);

    char timebuff[64];
    snprintf(timebuff, sizeof(timebuff), "%4d-%02d-%02d %02d-%02d-%02d",
        curr.tm_year + 1900,
        curr.tm_mon + 1,
        curr.tm_mday,
        curr.tm_hour,
        curr.tm_min,
        curr.tm_sec);

    return timebuff;
}
//策略模式
class LogStrategy
{
public:
    virtual ~LogStrategy() = default;
    //不同的模式有不同的刷新策略
    virtual void SyncLog(const std::string &message) = 0;
};
//显示器刷新
class ConsoleLogStrategy : public LogStrategy
{
public:
    //这里的构造函数直接用默认构造
    ~ConsoleLogStrategy()
    {}
    //刷新
    void SyncLog(const std::string &message) override
    {
        LockGuard LockGuard(&_lock);
        std::cout << message << std::endl;
    }
private:
    Mutex _lock;
};
//文件中刷新
class FileLogStrategy : public LogStrategy
{
public:
    //构造函数
    FileLogStrategy(std::string dir = defaultpath, std::string name = defaultname)
        :_logpath(dir), _logfilename(name)
        {
            LockGuard lockguard(&_lock);
            //判断是否存在该文件
            if(std::filesystem::exists(_logpath))
                return;
            //不存在就创建，但是要注意如果没有创建成功可能是权限问题，所以这里我们需要抛异常
            try
            {
                std::filesystem::create_directories(_logpath);
            }
            catch(const std::filesystem::filesystem_error &e)
            {
                std::cerr << e.what() << '\t\n';
            }
        }
     //将信息写入文件中
    void SyncLog(const std::string &message) override
    {
        LockGuard lockguard(&_lock);
        std::string log = _logpath + _logfilename;
        std::ofstream out(log.c_str(), std::ios::app); // 追加方式
        if (!out.is_open())
            return;
        out << message << "\n";
        out.close();
    }
     //析构函数
     ~FileLogStrategy() {}
private:
    //文件路径 & 文件名
    std::string _logpath;
    std::string _logfilename;
    Mutex _lock;
};

//2.构建一条完整的日志
class Logger
{
public:
    //构造函数
    Logger()
    {}
    //刷新策略
    void EnableConsoleLogStrategy()
    {
        _strategy = std::make_unique<ConsoleLogStrategy>();
    }
    void EnableFileLogStrategy()
    {
        _strategy = std::make_unique<FileLogStrategy>();
    }
    //创建一个内部类(拼接日志信息)
    class LoggerMessage
    {
    public:
        //构造函数
        LoggerMessage(LogLevel level, std::string &filename, int line, Logger &logger)
            :_time(Getcurrenttime()),
             _level(level),
             _pid(getpid()),
             _filename(filename),
             _line(line),
             _logger(logger)
        {
            //该函数可以将字符拼接成一个长串
            std::stringstream ss;
            ss << "[" << _time << "] "
                << "[" << level2string(_level) << "] "
                << "[" << _pid << "] "
                << "[" << _filename << "] "
                << "[" << _line << "] "
                << "- ";
            _loginfo = ss.str();
        }
        //<< 运算符重载
        template<typename T>
        LoggerMessage& operator<<(const T& info)
        {
            std::stringstream ss;
            ss << info;
            _loginfo += ss.str();
            return *this;
        }
        //析构函数
        ~LoggerMessage()
        {
            if(_logger._strategy)
            {
                _logger._strategy->SyncLog(_loginfo);
            }
        }
    private:
        std::string _time; //时间
        LogLevel _level; //日志等级
        pid_t _pid; //进程pid
        std::string _filename; //文件名
        int _line; //行号

        std::string _loginfo; //一条完整日志
        Logger &_logger; //提供刷新策略的具体方法
    };
    //重载()运算符
    LoggerMessage operator()(LogLevel level, std::string filename, int line)
    {
        return LoggerMessage(level, filename, line, *this);
    }
    //析构函数
    ~Logger()
    {}
private:
    std::unique_ptr<LogStrategy> _strategy;
};

Logger logger;

#define LOG(level) logger(level, __FILE__, __LINE__)
#define EnableConsoleLogStrategy() logger.EnableConsoleLogStrategy()
#define EnableFileLogStrategy() logger.EnableFileLogStrategy()